<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--部门数据-->
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input v-model="deptName" placeholder="请输入部门名称" clearable prefix-icon="Search" style="margin-bottom: 20px" />
        </div>
        <div class="head-container">
          <el-tree
            :data="deptOptions"
            :props="{ label: 'label', children: 'children' }"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="deptTreeRef"
            node-key="id"
            highlight-current
            default-expand-all
            @node-click="handleNodeClick"
          />
        </div>
      </el-col>
      <!--用户数据-->
      <el-col :span="20" :xs="24">
        <div class="app-container__section" >
          <PlusSearch :columns="columns" v-bind="searchBinds" @reset="onResetFn"></PlusSearch>
        </div>
        <div class="app-container__section">
          <PlusTable v-bind="tableBinds" :columns="columns">
            <template #title>
              <table-title />
            </template>
            <template #plus-cell-status="scope">
              <el-switch inactive-color="1" active-value="0"  @click="handleStatusChange(scope.row)"  :model-value="scope.row.status"></el-switch>
            </template>
            <template #toolbar>
              <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['system:user:add']">新增</el-button>
              <el-button type="success" plain icon="Edit" :disabled="gSelection.length !== 1" @click="handleUpdate" v-hasPermi="['system:user:edit']">修改</el-button>
              <el-button type="danger" plain icon="Delete" :disabled="!gSelection.length" @click="handleDelete(gSelection)" v-hasPermi="['system:user:remove']">删除</el-button>
<!--              <el-button type="info" plain icon="Upload" @click="handleImport" v-hasPermi="['system:user:import']">导入</el-button>-->
              <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['system:user:export']">导出</el-button>
              <ClockTimer :task="gGetList" />
              <SearchAreaControl v-model="gShowSearchForm" />
            </template>
            <template #plus-cell-action="scope">
              <el-tooltip content="修改" placement="top" v-if="scope.row.userId !== 1">
                <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:user:edit']"></el-button>
              </el-tooltip>
              <el-tooltip content="删除" placement="top" v-if="scope.row.userId !== 1">
                <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:user:remove']"></el-button>
              </el-tooltip>
              <el-tooltip content="重置密码" placement="top" v-if="scope.row.userId !== 1">
                <el-button link type="primary" icon="Key" @click="handleResetPwd(scope.row)" v-hasPermi="['system:user:resetPwd']"></el-button>
              </el-tooltip>
              <el-tooltip content="分配角色" placement="top" v-if="scope.row.userId !== 1">
                <el-button link type="primary" icon="CircleCheck" @click="handleAuthRole(scope.row)" v-hasPermi="['system:user:edit']"></el-button>
              </el-tooltip>
            </template>
          </PlusTable>
        </div>
      </el-col>
    </el-row>

    <!-- 添加或修改公告对话框 -->
    <addForm ref="addFormRef" @refreshList="gGetList" />
  </div>
</template>

<script setup >
import { useColumnsDict, useCommonConfig } from './hook.js'
import { useDelHook, useListHook } from '@/hooks/crud/index.js'
import { useListConfigHook } from '@/hooks/usePlusConfigHook.js'
import AddForm from './addForm.vue'
import { resetUserPwd, deptTreeSelect, changeUserStatus } from '@/api/system/user.js'
import { formatRangeTime } from '@/utils/index.js'
defineOptions({
  name: 'User'
})
const { proxy, primaryKey, apiFn,moduleName,beforeDelFn,deptOptions } = useCommonConfig()
const { dictData, columns, } = useColumnsDict()
const router = useRouter();
// ====================列表逻辑=========================
const gSearchForm = ref({  })
const { gGetList, gAllExposeOption,gReset } = useListHook({
  listApiFn:apiFn.listApiFn,
  gSearchForm,
  beforeRequest: (reqData) => {
    let { createTime, ...rest } = reqData;
    let timeRange = formatRangeTime(createTime,undefined,'YYYY-MM-DD')
    return {
      ...rest,
      params:timeRange
    }
  },
  afterRequest: (resData) => {
    return resData
  }
})
// ===================左侧树逻辑======================
const deptName = ref('')
// 节点单击事件
function handleNodeClick(data) {
  gSearchForm.value.deptId = data.id
  gGetList()
}
// 通过条件过滤节点
const filterNode = (value, data) => {
  if (!value) return true
  return data.label.indexOf(value) !== -1
}
// 根据名称筛选部门树
watch(deptName, (val) => {
  proxy.$refs['deptTreeRef'].filter(val)
})

// ====================属性绑定=========================
const { gTableBinds, gSearchBinds, gSelection, gShowSearchForm } = useListConfigHook()
const tableBinds = computed(() => gTableBinds({ ...gAllExposeOption,primaryKey }))
const searchBinds = computed(() => gSearchBinds({ ...gAllExposeOption }, ['reset'] ))
const onResetFn = ()=>{
  proxy.$refs['deptTreeRef'].setCurrentKey(null)
  gReset ()
}

// ==================删除逻辑===========================
const { gDelete } = useDelHook({
  delApiFn:apiFn.delApiFn,
  moduleName,
  beforeDelFn: (reqData) => beforeDelFn(reqData) ,
  afterDelFn: (resData) => {
    gGetList()
  }
})
const handleDelete = (data)=>{
  gDelete(data)
}
// ===================新增、修改======================
const addFormRef = ref(null)
// 新增操作
function handleAdd() {
  addFormRef.value.gOpen()
}
// 修改操作
function handleUpdate(row) {
  addFormRef.value.gOpen(row)
}
// ========================================

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    'system/user/export',
    {
      ...gSearchForm.value
    },
    `user_${new Date().getTime()}.xlsx`
  )
}

/** 用户状态修改  */
function handleStatusChange(row) {
  let text = row.status === '0' ? '启用' : '停用'
  proxy.$modal
    .confirm('确认要"' + text + '""' + row.userName + '"用户吗?')
    .then(function () {
      return changeUserStatus(row.userId, row.status)
    })
    .then(() => {
      proxy.$modal.msgSuccess(text + '成功')
    })
    .catch(function () {
      row.status = row.status === '0' ? '1' : '0'
    })
}
/** 更多操作 */
function handleCommand(command, row) {
  switch (command) {
    case 'handleResetPwd':
      handleResetPwd(row)
      break
    case 'handleAuthRole':
      handleAuthRole(row)
      break
    default:
      break
  }
}
/** 跳转角色分配 */
function handleAuthRole(row) {
  const userId = row.userId
  router.push('/system/user-auth/role/' + userId)
}
/** 重置密码按钮操作 */
function handleResetPwd(row) {
  proxy
    .$prompt('请输入"' + row.userName + '"的新密码', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      closeOnClickModal: false,
      inputPattern: /^.{5,20}$/,
      inputErrorMessage: '用户密码长度必须介于 5 和 20 之间'
    })
    .then(({ value }) => {
      resetUserPwd(row.userId, value).then((response) => {
        proxy.$modal.msgSuccess('修改成功，新密码是：' + value)
      })
    })
    .catch(() => {})
}
</script>
